package com.captjack.micro.service.article.impl;

import com.captjack.micro.api.article.MicroServiceTwo;
import com.captjack.micro.dao.es.entity.Article;
import com.captjack.micro.dao.es.entity.Author;
import com.captjack.micro.dao.es.entity.Tutorial;
import com.captjack.micro.dao.es.repository.ArticleSearchRepository;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;

/**
 * Description description.....
 *
 * @author Jack Sparrow
 * @version 1.0.0
 * @date 2018/6/21 23:15
 * package com.captjack.micro.service.article.impl
 */
@Slf4j
@RestController
public class MicroServiceTwoImpl implements MicroServiceTwo {

    /**
     *
     */
    private final ArticleSearchRepository articleSearchRepository;

    @Override
    public String service() {
        QueryBuilder queryBuilder = QueryBuilders.rangeQuery("clickCount").from(1);
        // 查询
        Iterable<Article> searchResult = articleSearchRepository.search(queryBuilder);
        searchResult.forEach(System.out::println);
        return searchResult.toString();
    }

    /**
     * 插入一条数据
     *
     * @return 插入的数据
     */
    private String esSave() {
        try {
            Random random = new Random();
            Author author = new Author();
            author.setId(random.nextLong());
            author.setName("tianshouzhi");
            author.setRemark("java developer");

            Tutorial tutorial = new Tutorial();
            tutorial.setId(random.nextLong());
            tutorial.setName("elastic search");

            Article article = new Article();
            article.setId(random.nextLong());
            article.setTitle("springboot integreate elasticsearch");
            article.setAbstracts("springboot integreate elasticsearch is very easy");
            article.setTutorial(tutorial);
            article.setAuthor(author);
            article.setContent("elasticsearch based on lucene,"
                    + "spring-data-elastichsearch based on elaticsearch"
                    + ",this tutorial tell you how to integrete springboot with spring-data-elasticsearch");
            article.setPostTime(new Date());
            article.setClickCount(1L);
            Article result = articleSearchRepository.save(article);
            return result.toString();
        } catch (Exception e) {
            log.error("esSave error! cause by : ", e);
            return null;
        }
    }

    @Autowired
    public MicroServiceTwoImpl(ArticleSearchRepository articleSearchRepository) {
        this.articleSearchRepository = articleSearchRepository;
    }

}
